package com.ltmall.api.comm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ltmall.api.comm.json.City;
import com.ltmall.api.comm.json.Express;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ExpressParse {

    private static List<City> cityList = new ArrayList<>();
    // 注意filepath的内容
    static String filePath;

    public void test() {
        List<Express> expressList = excute();
        System.out.println(expressList.size());
    }


    public static String readFile() {
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    public static void initJsonPath(String path) {
        String certain = "resource" + File.separator + "express.json";
        filePath = path + certain;
    }

    public static List<Express> excute() {
        String JsonContext = readFile();
        JSONArray jsonArray = JSONArray.parseArray(JsonContext);
        List<Express> list = new ArrayList<Express>();
        int size = jsonArray.size();
        System.out.println("Size: " + size);
        for (int i = 0; i < size; i++) {
            Express express = new Express();

            JSONObject jObject = jsonArray.getJSONObject(i);
            String key = jObject.getString("expresskey");
            String name = jObject.getString("expressname");
            String webSite = jObject.getString("expresswebsite");
            String telephone = jObject.getString("expresstelephone");

            express.setKey(key);
            express.setExpressName(name);
            express.setExpressWebSite(webSite);
            express.setExpressTelephone(telephone);
            list.add(express);

        }
        return list;
    }

}